# include <TimeProfiler.hpp>

namespace FTSS
{
	
INT_32 TimeProfiler::StartPoint(CCHAR_P sPointName, Size_t iPointNameLength)
{
	TimeDelta oTimeDelta;
	gettimeofday(&oTimeDelta.tm_end, NULL);

	TokenHash_t iHash = HashFunc(sPointName, iPointNameLength);
	TimeHash::iterator ithData = oTimeHash.find(iHash, iHash);

	// New time point
	if (ithData == oTimeHash.end())
	{
		// Delta == 0
		oTimeDelta.tm_begin = oTimeDelta.tm_end;

		oTimeDelta.tm_delta.tv_sec  = 0;
		oTimeDelta.tm_delta.tv_usec = 0;

		oTimeHash.insert(TimePair(iHash, oTimeDelta), iHash);
		return 0;
	}

	ithData -> second.tm_begin = ithData -> second.tm_end;
	ithData -> second.tm_end   = oTimeDelta.tm_end;

	return -1;
}	

W_FLOAT TimeProfiler::EndPoint(CCHAR_P sPointName, Size_t iPointNameLength)
{
	TimeDelta oTimeDelta;
	gettimeofday(&oTimeDelta.tm_end, NULL);
	TokenHash_t iHash = HashFunc(sPointName, iPointNameLength);
	TimeHash::iterator ithData = oTimeHash.find(iHash, iHash);
	if (ithData != oTimeHash.end())
	{
		long lTDSec  = oTimeDelta.tm_end.tv_sec  - ithData -> second.tm_end.tv_sec;
		long lTDUSec = oTimeDelta.tm_end.tv_usec - ithData -> second.tm_end.tv_usec;

		ithData -> second.tm_delta.tv_sec  += lTDSec;
		ithData -> second.tm_delta.tv_usec += lTDUSec;

		ithData -> second.tm_begin = ithData -> second.tm_end;
		ithData -> second.tm_end   = oTimeDelta.tm_end;

		return (lTDSec  * 1000.0 +
		        lTDUSec / 1000.0);
	}

	return -1.0;
}
	
}
